package utils

import (
	"context"
	"log"
	"time"

	"github.com/go-redis/redis/v8"
)

var RedisClient *redis.Client

// InitRedis 初始化Redis连接
func InitRedis(addr, password string, db int) error {
	RedisClient = redis.NewClient(&redis.Options{
		Addr:     addr,
		Password: password,
		DB:       db,
	})

	// 检查连接
	ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
	defer cancel()

	_, err := RedisClient.Ping(ctx).Result()
	if err != nil {
		return err
	}

	log.Println("Connected to Redis!")
	return nil
}

// CloseRedis 关闭Redis连接
func CloseRedis() {
	if RedisClient != nil {
		_ = RedisClient.Close()
	}
}

// Redis操作封装
func Set(key string, value interface{}, expiration time.Duration) error {
	ctx := context.Background()
	return RedisClient.Set(ctx, key, value, expiration).Err()
}

func Get(key string) (string, error) {
	ctx := context.Background()
	return RedisClient.Get(ctx, key).Result()
}

func Del(key string) error {
	ctx := context.Background()
	return RedisClient.Del(ctx, key).Err()
}

func HSet(key string, values ...interface{}) error {
	ctx := context.Background()
	return RedisClient.HSet(ctx, key, values...).Err()
}

func HGet(key, field string) (string, error) {
	ctx := context.Background()
	return RedisClient.HGet(ctx, key, field).Result()
}
